package com.robooot.business_counter.config.interceptor;



import com.robooot.business_counter.exception.BizException;
import com.robooot.business_counter.exception.DemoError;
import com.robooot.business_counter.model.RemoteUrl;
import com.robooot.business_counter.model.Token;
import com.robooot.business_counter.service.RemoteService;
import com.robooot.business_counter.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

//@Configuration
//public class SecurityInterceptor implements HandlerInterceptor {
//    public SecurityInterceptor() {
//        super();
//    }
//
//    @Autowired
//    private RemoteUrl remoteUrl;
//    @Autowired
//    private RemoteService remoteService;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        String bearerToken = request.getHeader("Authorization");
//        String token = null;
//        if (bearerToken == null || !bearerToken.startsWith("Bearer ")) {
//            Cookie[] cookies = request.getCookies();
//            if (cookies != null) {
//                for (int i = 0; i < cookies.length; i++) {
//                    if ("COOKIE_PERM".equals(cookies[i].getName())) {
//                        token = cookies[i].getValue();
//                        break;
//                    }
//                }
//            }
//        } else {
//            token = bearerToken.replaceFirst("Bearer ", "");
//        }
//        if (token == null) {
//            throw new BizException(DemoError.SYSTEM_ERROR);
//        }
//        try {
//            Map params = new HashMap();
//            params.put("token", token);
//            Map map = remoteService.callWithSign(remoteUrl.getToken(), params);
//            Token tokenUser = JsonUtil.object2Bean(map, Token.class);
//            Map json = map;
//            if (StringUtils.isBlank(tokenUser.getUserId())) {
//                throw new BizException(DemoError.SYSTEM_ERROR);
//            }
//            request.setAttribute("token", tokenUser);
//            return true;
//        } catch (Exception e) {
//            throw new BizException(300, e.getMessage());
//        }
//    }
//}